from django.contrib.auth.models import Permission, ContentType, Group
from users.models import User

from rest_framework.serializers import ModelSerializer


class PermissionSerialize(ModelSerializer):
    """
    用户权限序列化器
    """

    class Meta:
        model = Permission
        fields = '__all__'


class ContentTypeSerialzier(ModelSerializer):
    """
               权限类型序列化器
           """

    class Meta:
        model = ContentType
        fields = ('id', 'name')


class GroupSerialzier(ModelSerializer):
    class Meta:
        model = Group
        fields = "__all__"


class UserSerialzier(ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }

    def create(self, validated_data):
        # 添加管理员字段
        validated_data['is_staff'] = True
        password = validated_data["password"]
        user = super().create(validated_data)
        user.set_password(password)
        user.save()
        return user
